/*
 * $Id: CurrentUser.java 1406 2011-08-05 10:00:56Z abie $
 * 
 * Copyright (c) 2001-2008 Accentrix Company Limited. All Rights Reserved.
 * 
 * Accentrix Company Limited. ("Accentrix") retains copyright on all text, source
 * and binary code contained in this software and documentation. Accentrix grants
 * Licensee a limited license to use this software, provided that this copyright
 * notice and license appear on all copies of the software. The software source
 * code is provided for reference purposes only and may not be copied, modified 
 * or distributed.
 * 
 * THIS SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS," WITHOUT ANY WARRANTY OF
 * ANY KIND UNLESS A SEPARATE WARRANTIES IS PURCHASED FROM ACCENTRIX AND REMAINS
 * VALID.  ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. ACCENTRIX SHALL NOT BE LIABLE
 * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING OR MODIFYING THE
 * SOFTWARE OR ITS DERIVATIVES.
 * 
 * IN NO EVENT WILL ACCENTRIX BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
 * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE
 * USE OF OR INABILITY TO USE SOFTWARE, EVEN IF ACCENTRIX HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */
package com.lightsaber.trade.core.common.util;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springside.modules.utils.spring.SpringContextHolder;

import com.lightsaber.trade.core.dao.account.UserDao;
import com.lightsaber.trade.core.entity.account.Organization;
import com.lightsaber.trade.core.entity.account.Role;
import com.lightsaber.trade.core.entity.account.User;

/**
 * Get the user who login HPP system successfully.
 * 
 * @author LiuJian
 * 
 */
public final class CurrentUser {

    private final static Logger log = LoggerFactory.getLogger(CurrentUser.class);

    public final static String ANONYMOUS_USER = "anonymousUser";

    private CurrentUser() {
    }

    public static User get() {
        String loginId = getName();
        if (StringUtils.isBlank(loginId)) {
            return null;
        }

        UserDao userProfileDao = SpringContextHolder.getBean(UserDao.class);
        User user = userProfileDao.findUniqueBy("loginId", loginId);

        log.info("CurrentUser is {}", loginId);
        return user;
    }

    public static Organization getOrg() {
        return get().getOrganization();
    }

    /**
     * just used for testing
     */
    private static final ThreadLocal<String> currentUser = new ThreadLocal<String>();

    public static void setCurrentUser(final String username) {
        currentUser.set(username);
    }

    public static void removeCurrentUser() {
        currentUser.remove();
    }

    public static String getName() {

        String username = currentUser.get();
        if (username != null) {
            return username;
        }

        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            log.error("SecurityContext is null");
            return null;
        }

        Authentication authentication = ctx.getAuthentication();
        if (authentication == null) {
            log.error("Authentication is null");
            return null;
        }

        username = authentication.getName();
        if (StringUtils.equals(ANONYMOUS_USER, username)) {
            return null;
        }

        return username;
    }

    public static String[] getRolesAsArrays() {
        User user = get();

        List<Role> roleList = user.getRoleList();
        String[] roles = new String[roleList.size()];

        for (int i = 0; i < roleList.size(); i++) {
            roles[i] = roleList.get(i).getName();
        }

        if (log.isDebugEnabled()) {
            log.debug("Current user {}'s roles is {}", getName(),
                    ToStringBuilder.reflectionToString(roles));
        }

        return roles;
    }

    /**
     * @return Roles which is char set separated by ","<br>
     *         Example: "'administrator', 'endorser','planner'"
     */
    public static String getRoles() {
        String[] rolesAsArrays = getRolesAsArrays();
        StringBuilder roles = new StringBuilder();

        for (String role : rolesAsArrays) {
            roles.append(",'" + role + "'");
        }

        log.debug("Current user {}'s roles is {}", getName(), roles.toString());

        if (roles.length() > 0) {
            return roles.substring(1);
        }

        return "ANONYMOUS";
    }

}
